from lib.uplink import Uplink
import os, shutil, zipfile
import settings

class CheckOut():
    def __init__(self):
        self.uplink = Uplink(settings.REST_SERVER)

    def getversion(self, url):
        try:
            f = open(url+'version')
            version = f.read()
            f.close()
            return version
        except:
            return -1

    def run(self, path, log, force = False):
          fulldestination = settings.TRUNK + path
          fullsource = settings.REST_PATH + path
          if not force:
              version = self.getversion(fulldestination)
          else:
              version = -1
          print 'V =',version, 'fulldestination = ',fulldestination
          status, response = self.uplink.GET(fullsource + str(version))
          if status==200:
              try:
                  shutil.rmtree(fulldestination)
              except:
                  pass
              os.makedirs(fulldestination)
              self.uplink.store_file(fulldestination+'extras.zip',response)
              z = zipfile.ZipFile(fulldestination+'extras.zip')
              z.extractall(fulldestination)
              z.close()
              log.debug('%s was updated', path)
              return True
          if status==201:
              log.debug('%s wasn\'t changed', path)
              return True
          return False